// 用户的路由
const express = require("express");
let { uploading } = require("../utils")  //引入工具
let router = express.Router();
const fs = require("fs")
// 引入用户数据库模型
const userModel = require("../models/usermodel.js");
// 引入加密数据的模块  md5
const md5 = require("md5")


router.get("/getdata", async (req, res) => {

    try {
        let { p } = req.query;
        console.log(p);
        let userData = await userModel.find();
        // 获取对应的页码数据
        let totalCount = userData.length;   //数据的总条数
        // console.log(totalCount);
        let perpage = 2; //每页展示的条数
        let totalpage = Math.ceil(totalCount / perpage);  //页码数

        // 展示的数据
        let showdata = await userModel.find().skip((p - 1) * perpage).limit(perpage)
        res.json({
            info: "获取成功",
            status: 1,
            users: showdata,
            totalpage
        })
    } catch (err) {
        console.log(err);
        res.json({
            info: "获取失败",
            status: 0
        })
    }
})

router.post("/adduser", async (req, res) => {

    try {
        let result = await uploading(req);
        // console.log(result);
        result.pwd = md5(result.pwd);   //加密密码
        result.time = new Date().toLocaleDateString()  //添加时间
        // console.log(result);
        let resobj = await userModel.create(result);   //添加数据
        console.log(resobj);

        res.json({
            info: "添加成功",
            status: 1,

        })
    } catch (err) {
        console.log(err);
        res.json({
            info: "添加失败",
            status: 0
        })
    }
})


// 删除数据的路由
router.delete("/deluser", async (req, res) => {
    // 获取传过来的id值
    let _id = req.query

    let userdata = await userModel.find(_id);
    let imgurl = userdata[0].imgurl
    // 删除对应数据的 图片
    fs.unlink('./static/' + imgurl, (err) => {
        if (err) {
            return console.log(err);
        }
        console.log("删除成功");
    })
    // 通过id值 来进行数据库删除
    try {
        let resdata = await userModel.deleteOne(_id)
        res.json({
            info: "删除成功",
            status: 1
        })
    } catch (err) {

        console.log(err);
        res.json({
            info: "删除失败",
            status: 0
        })
    }
})

module.exports = router;